/**
 * 值转换为数字
 * @param {any} str - 被转换的值
 * @param {number} decimal - 转换后保留的位数
 */
export const parseNumber = (str = 0, decimal = 2) => {
  const num = +str

  if (isNaN(num)) return 0

  const x = Math.pow(10, decimal)
  return Math.round(num * x) / x
}

/**
 * 获取值的类型
 * @param {any} val
 * @returns {string} - [string, number, array, object, null, undefined]
 */
export const typeof2 = (val) => {
  const str = Object.prototype.toString.call(val)
  return str.substring(8, str.length - 1).toLocaleLowerCase()
}

/**
 * 浅拷贝
 */
export const copy = value => {
  let result = value

  try {
    result = JSON.parse(JSON.stringify(result))
  } catch (err) {
    console.log(err)
  }

  return result
}

/**
 * 获取参数列表中符合值的标题名
 * @param {array} data
 * @param {string|number|boolean|null} data
 */
export const parseByValue = (data, value) => {
  const i = data.find(el => el.value === value)

  return i ? i.label : value
}

// 四舍五入保留x位小数（不够位数，则用0替补）
export const keepDecimalFull = (num, x = 2) => {
  let result = parseFloat(num)
  if (isNaN(result)) {
    console.error(`传递参数：${num} 错误，请检查！`)
    return ''
  }
  const bit = Math.pow(10, x)
  result = Math.round(num * bit) / bit
  let sX = result.toString()
  let posDecimal = sX.indexOf('.')
  if (posDecimal < 0) {
    posDecimal = sX.length
    sX += '.'
  }
  while (sX.length <= posDecimal + x) {
    sX += '0'
  }
  return sX
}
